<template>
  <el-dialog v-model="isShow" :title="title" width="500">
    <el-form
      :model="formData"
      label-width="auto"
      style="max-width: 600px"
      ref="formRef"
      :rules="rules"
    >
      <el-form-item label="会议室名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="位置" prop="location">
        <el-input v-model="formData.location" />
      </el-form-item>
      <el-form-item label="容量" prop="capacity">
        <el-input v-model="formData.capacity" style="width: 80px" />
      </el-form-item>
      <el-form-item label="设备" prop="equipment">
        <el-input v-model="formData.equipment" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)"> 创建 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { createMeetingRoom } from '@/api'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { onMounted, reactive, ref, type PropType } from 'vue'
import type { IMeetingRoomResult } from './index.vue'

// 基于运行时的声明
const props = defineProps({
  title: {
    type: String,
    default: '创建会议室',
    required: false
  },
  info: {
    type: Object as PropType<IMeetingRoomResult | null>,
    required: false
  }
})
const emits = defineEmits<{
  onSubmit: [formData: IMeetingRoomFormData]
}>()

export interface IMeetingRoomFormData {
  id?: number
  name: string
  location: string
  capacity: string | number
  equipment: string
  description: string
}

const isShow = defineModel<boolean>()
const formRef = ref<FormInstance>()
let formData = reactive<IMeetingRoomFormData>({
  name: '',
  location: '',
  capacity: '',
  equipment: '',
  description: ''
})
const rules = reactive<FormRules<IMeetingRoomFormData>>({
  name: [{ required: true, message: '请输入会议室名称', trigger: 'blur' }],
  location: [{ required: true, message: '请输入位置', trigger: 'blur' }],
  capacity: [{ required: true, message: '请输入容量', trigger: 'blur' }]
})

onMounted(() => {
  if (props.info) {
    formData = Object.assign(formData, props.info)
  }
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      emits('onSubmit', formData)
    } else {
      ElMessage.error('表单校验失败')
    }
  })
}
</script>

<style scoped></style>
